<template>
  <el-row :gutter="20">
    <el-col :span="8">
      <el-tree :data="treeData"
               :props="defaultProps"
               @node-click="handleNodeClick"
               node-key="id"
               :default-checked-keys="[10]"></el-tree>
    </el-col>
    <el-col :span="16">
      <el-transfer v-model="value"
                   filterable
                   @change="onTransferChange"
                   filter-placeholder="请输入姓名"
                   :data="transferData"
                   :right-default-checked="sureData"
                   :titles="['成员', '已选择']"
                   @right-check-change="selectTransferData">
      </el-transfer>
    </el-col>
    <el-col :span="24"
            id="bottomBox">
      <el-button @click="onBack">取 消</el-button>
      <el-button type="primary"
                 @click="savePerson">确 定</el-button>

    </el-col>
  </el-row>
</template>
<script>
import { organizationApi } from '@/services/CompanySetting';
import { noteSettingApi } from "@/services/SystemSetting";
import { standardCodeApi } from '@/services/StandardCode'
import { openApi } from "@/services/SystemSetting";
export default {
  props: {
    todos: Number,
    catchBack: Function,
    catchSave: Function
  },
  data () {
    return {
      org_no: '',
      treeData: [],
      defaultProps: {
        children: 'children_list',
        label: 'name'
      },
      arr: [],
      value: [],
      selectData: '',
      transferData: [],
      sureData: [],
      compId: '',
      newAddArr: [],//新选中的数组
    }
  },
  methods: {
    //返回
    onBack () {
      this.catchBack('SUCCESS')
    },
    //组织管理
    getOrganization () {
      organizationApi.getOrgTree({
        data: {
          node_no: this.org_no,
          node_type: 1
        }
      }).then(res => {
        this.treeData = res.data;
        if (this.treeData.length != 0) {
          this.handleNodeClick(this.treeData[0])
        }
      })
    },
    //短信配置->添加->获取本单位下列表---->左边的列表数据
    getUnitList () {
      //console.log('左边company_id', this.company_id)
      openApi.getUnitListData({
        data: {
          org_no: parseInt(this.selectOrgNo),//正确的
          is_page: 0,
          company_id: parseInt(this.company_id)//单位的id
        }
      }).then((res) => {
        this.transferData = [];
        for (let i = 0; i < res.data.list.length; i++) {
          this.transferData.push({
            key: res.data.list[i].user_id,
            label: res.data.list[i].user_name
          });
        }
      }).catch((error) => {
        console.log(error)
      });
    },
    //已选中的人员---->右边的列表数据
    getSelectedList () {
      //已选人员列表
      noteSettingApi.getPersonList({
        params: {
          //company_id: this.selectOrgNo,
          company_id: this.company_id,
          org_no: this.selectOrgNo
        }
      }).then((res) => {
        console.log('已选中的人员---->右边的列表数据=', res.data)
        //获取右边的数组数据
        this.rightDataArr = []
        this.sureData = [];
        this.value = [];
        res.data.forEach(ele => {
          this.selectedArr.push(ele)
        })
        for (let j = 0; j < res.data.length; j++) {
          this.rightDataArr.push({
            key: res.data[j].admin_id,
            label: res.data[j].user_name
          });
        }

        for (let i = 0; i < this.selectedArr.length; i++) {
          //右边选中的
          if (this.selectedArr[i].is_delete == 2) {
            this.sureData.push((this.selectedArr[i].admin_id).toString());
          }
          //右边有的
          this.value.push((this.selectedArr[i].admin_id).toString());
        }
        //获取原始右边有值的列表id
        this.rightMrArr = this.value;
        //获取原始右边有值的列表数据；
        this.rightMrArrList = this.selectedArr;
      }).catch((error) => {
        console.log(error)
      })
    },
    //选择单位
    handleNodeClick (data) {
      this.selectOrgNo = data.org_no;
      this.company_id = data.company_id;
      this.selectData = '';
      this.value = [];//右边的数据清空
      this.sureData = [];//右边已有的值
      this.selectedArr = [];//右边数组对象
      //console.log('右边的数据=', this.value);
      //短信配置->添加->获取本单位下列表
      this.getUnitList();
      //已选中的人员
      this.getSelectedList();
    },
    onTransferChange (val) {
      this.selectedArr = [];
      //左边空梭到右边后,对应的数组对象重命名
      if (this.value.length != 0 && this.value[0] != "") {
        for (var i = 0; i < this.value.length; i++) {
          for (var j = 0; j < this.transferData.length; j++) {
            if (this.value[i] == this.transferData[j].key) {
              this.selectedArr.push({
                admin_id: this.transferData[j].key,
                user_name: this.transferData[j].label,
                is_delete: 1,
                company_id: '',
                created_at: '',
                project_id: '',
                sms_admin_id: '',
                updated_at: ''
              });
            }
          }
        }
      } else {
        //不满足条件的右边的则为空
        this.value = [];
        this.selectedArr = [];
      }
      //右边已有的列表数据值还原；
      for (var i = 0; i < this.rightMrArrList.length; i++) {
        for (var j = 0; j < this.selectedArr.length; j++) {
          if (this.rightMrArrList[i].admin_id == this.selectedArr[j].admin_id) {
            this.selectedArr[j] = this.rightMrArrList[i]
          }
        }
      }
    },
    selectTransferData (data) {
      this.selectData = data.join(',')//保存时判断is_delete是否为0：未选中；1：已选中
      this.arr = this.selectData.split(',');
      console.log('最初arr=', this.arr)
    },
    //保存选中人员
    savePerson () {
      //判断右边是否有选中
      if (this.value.length == 0 || this.value[0] == "") {
        this.$message.warning('请选择人员')
      } else {
        //console.log('this.arr=', this.arr)
        //保存前判断右边是否有选中
        if ((this.arr.length == 1 && this.arr[0] == "") || this.arr.length == 0) {
          //右边------没选中的设置为1
          this.selectedArr.map(item => {
            item.is_delete = 1;
          })
        } else {
          //右边------被选中的设置为2
          this.selectedArr.map(item => {
            if (this.arr.includes((item.admin_id).toString()) == true) {
              item.is_delete = 2;
            }
          });
          //右边------没选中的设置为1
          this.selectedArr.map(item => {
            if (this.arr.includes((item.admin_id).toString()) != true) {
              item.is_delete = 1;
            }
          })
        };
        noteSettingApi.setProjectUserChange({
          data: {
            // admin_ids: this.selectData
            user_list: JSON.stringify(this.selectedArr),
            project_id: this.$route.query.project_id,
            company_id: this.company_id,
            org_no: this.selectOrgNo
          }
        }).then((res) => {
          if (res.code == 0) {
            this.$message.success('添加成功');
            this.catchSave('SUCCESS');
            // this.page = 1;
            // this.getProNoteData();
            this.selectData = '';
            // this.addVisible = false;
          }
        }).catch((error) => {
          console.log(error)
        })
      }
    },
  },
  watch: {
    todos (n, o) {
      if (n == 1) {
        this.org_no = JSON.parse(window.localStorage.userInfo).org_no;
        //判断id是否为空
        if (this.org_no != undefined) {
          //获取组织树
          this.getOrganization()
        }
      } else {

      }
      console.log('watch----todos=', n)
    }
  },
  created () {
    console.log('created----todos=', this.todos);
    this.org_no = JSON.parse(window.localStorage.userInfo).org_no;
    //判断id是否为空
    if (this.org_no != undefined) {
      //获取组织树
      this.getOrganization()
    }
  }
}
</script>

<style  lang="scss" scoped>
#bottomBox {
  text-align: right;
  margin-top: 40px;
}
</style>